package com.indictor.bean;

import com.indicator.base.constant.ControllerConstants;
import com.indictor.conf.RedisConfig;
import io.lettuce.core.api.sync.RedisCommands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.indicator.base.constant.ControllerConstants.FORMULA_REDIS;
import static com.indicator.base.constant.ControllerConstants.INDICATOR_REDIS;


public class DefaultIndicatorManager implements IndicatorManager {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public IndicatorCommand findIndicator(String key) {
        Assert.isTrue(key != null && !key.equals(""), "关键字：" + key + "不可以为空");
        return doFindIndicators(key);
    }

    private IndicatorCommand doFindIndicators(String key) {
        IndicatorApplicationContext context = IndicatorApplicationContext.getInstance();
        IndicatorCommand indicatorCommand = context.get(key);
        if (indicatorCommand != null) {
            logger.info("关键字 key" + key + " 命中缓存");
            return indicatorCommand;
        }
        RedisCommands redisCommands = RedisConfig.getInstance().get();
        //查询出所有的子key
        List<String> zrange = redisCommands.zrevrange(FORMULA_REDIS + key, 0, -1);
        if (zrange == null || zrange.isEmpty()) {
            logger.info("not find  subkeys from key " + key);
            return indicatorCommand;
        }
        List<Indicator> indicators = new ArrayList<>(zrange.size());
        for (String indicatorStr : zrange) {
            int length = indicatorStr.length();
            String substring = indicatorStr.substring(0, length - 1);
            logger.info(key + ": has subkey have " + substring);
            Map<String, String> stringMap = redisCommands.hgetall(INDICATOR_REDIS + substring);
            String value = stringMap.get(ControllerConstants.COMPUTE_TYPE_DEFAULT_VALUE);
            Indicator indicator = new Indicator(substring, indicatorStr.substring(length - 1, length), StringUtils.isEmpty(value) ? null : new BigDecimal(value));
            indicators.add(indicator);
            indicatorStr = null;
        }
        zrange = null;
        indicatorCommand = new IndicatorCommand(key, indicators);
        context.put(key, indicatorCommand);
        for (Indicator indicator : indicators) {
            doFindIndicators(indicator.getKey());
        }
        return indicatorCommand;
    }
}
